<?php

require 'config.php';
require 'vendor/autoload.php';

use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;

// Download：https://github.com/aliyun/openapi-sdk-php
// Usage：https://github.com/aliyun/openapi-sdk-php/blob/master/README.md



function getHtml()
{
    $opts = [
        "http" => [
            "method" => "GET",
            "header" => "Accept-language: en\r\n" .
                "User-Agent: Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B334b Safari/531.21.102011-10-16 20:23:10\r\n" // i.e. An iPad 
        ]
    ];
    $url = 'http://www.cip.cc/';
    $context = stream_context_create($opts);
    $text = file_get_contents($url, false, $context);
    return $text;
}

function getIp()
{

    $text =  getHtml();
    $path = '/[\d]+\.[\d]+\.[\d]+\.[\d]+/';
    $matches = [];
    preg_match($path, $text, $matches);
    return $matches[0] ?? '';
}
$ipCurrent = getIp();
if (empty($ipCurrent)) {
    die('ip server error');
}

$ipLastest = (string)(file_get_contents('ip.txt'));
if ($ipCurrent === $ipLastest) {
    die('not change: current ip is ' . $ipLastest);
}


try {
    
    AlibabaCloud::accessKeyClient(ACCESS_KEY_ID, ACCESS_SECRET)
        ->regionId('cn-hangzhou')
        ->asDefaultClient();


    $recordId = RECORD_IDS;

    $result = AlibabaCloud::rpc()
        ->product('Alidns')
        // ->scheme('https') // https | http
        ->version('2015-01-09')
        ->action('UpdateDomainRecord')
        ->method('POST')
        ->host('alidns.aliyuncs.com')
        ->options([
            'query' => [
                'RegionId' => "cn-hangzhou",
                'RecordId' => $recordId,
                'RR' => RRS,
                'Type' => TYPE,
                'Value' => $ipCurrent,
            ],
        ])
        ->request();
    /*
     * 错误走异常
    if (!empty($result->Code)) {
        die('错误 code:'."[$result->Code] message: [$result->Message]");
    }
    */
    file_put_contents('ip.txt', $ipCurrent);
} catch (ClientException $e) {
    echo 'client exception: ' . $e->getErrorMessage() . PHP_EOL;
} catch (ServerException $e) {
    echo 'server exception:' . $e->getErrorMessage() . PHP_EOL;
}

echo 'changed to ' . $ipCurrent;
